﻿#include "webview.h"
#include "explore.h"


WebView::WebView(QWidget *parent)
    : QWebEngineView(parent),
    m_progress(100)
{
//    connect(this, &QWebEngineView::loadStarted, CustomProgressBar::instance(), &CustomProgressBar::handleStartProgress);
//    connect(this, &QWebEngineView::loadProgress, CustomProgressBar::instance(), &CustomProgressBar::handleLoadProgress);
//    connect(this, &QWebEngineView::loadFinished, CustomProgressBar::instance(), &CustomProgressBar::handleEndProgress);

    QLayout * layout = QWebEngineView::layout();
    progress = new CustomProgressBar();
    progress->setFixedHeight(2);
    progress->setTextVisible(false);
    layout->addWidget(progress);
    connect(this, &QWebEngineView::loadStarted, this, [=](){
        emit urlChanged(url());
        // 记录访问记录
        if(url().toString().length() >= 0){
            RecordHistoryThread * thread = new RecordHistoryThread(url().toString());
            thread->start();
        }
        m_progress = 0;
        if(!URLChecker::instance()->check(url().toString())){
            if(GlobalData::instance()->get(url().toString()) == GlobalData::boolFalse){
//                qDebug()<<"黑名单中的url";
                emit urlNotSafe(url().toString());
                stop();
            }
        }
        progress->show();
        emit loadStartedWebView();
    });
    connect(this, &QWebEngineView::loadProgress, this, [=](int val){
        m_progress = val;
        progress->setValue(val);
        emit loadProgressWebView(val);
    });
    connect(this, &QWebEngineView::loadFinished, this, [=](bool success){
        progress->setValue(0);
        progress->hide();
        layout->removeWidget(progress);   // QWebEngineView应该是使用chronium的渲染模式，使用完之后把组件去掉（如果开始的时候不使用tabwidget可能使用其他方式效果更好，不过非要使用的话目前这种效果还可以接受）
        emit loadFinishedWebView(success);
        emit checkUrlIsMark(url().toString());
    });

    // 加载icon
    connect(this, &QWebEngineView::iconChanged, [=](const QIcon &icon){
        emit favIconChanged(favIcon());
    });
}

void WebView::setWebPage(WebPage *page)
{
    // 替换当前page
    QWebEngineView::setPage(page);
    // 设置page相关信号和槽

    // 证书验证错误，停止加载请求
    connect(page, &WebPage::certificateErrorSignal, this, [=]{
//        qDebug()<<"stop request";
        stop();
        QWebEngineView::setPage(nullptr);
    });
}

QWebEngineView * WebView::createWindow(QWebEnginePage::WebWindowType type){
    MainWindow *mainWindow = qobject_cast<MainWindow*>(window());
    if (!mainWindow)
        return nullptr;

    switch (type) {
        case QWebEnginePage::WebBrowserTab: {
            return mainWindow->tabWidget()->createTab();
        }
        case QWebEnginePage::WebBrowserBackgroundTab: {
            return mainWindow->tabWidget()->createBackgroundTab();
        }
        case QWebEnginePage::WebBrowserWindow: {
            return mainWindow->explore()->createWindow()->currentTab();
        }
        case QWebEnginePage::WebDialog: {
            return mainWindow->explore()->createWindow()->currentTab();
        }
    }
    return nullptr;
}

QIcon WebView::favIcon() const
{
    QIcon favIcon = page()->icon();
    qDebug() << "icon = "<<(page()->icon().isNull()) <<" url = "<<url();
    if (!favIcon.isNull()){
        return favIcon;
    }

    if (m_progress < 0) {
        static QIcon errorIcon(QStringLiteral(":/safe_explore_resource/dialog-error.png"));
        return errorIcon;
    } else if (m_progress < 100) {
        static QIcon loadingIcon(QStringLiteral(":/safe_explore_resource/view-refresh.png"));
        return loadingIcon;
    } else {
        static QIcon defaultIcon(QStringLiteral(":/safe_explore_resource/text-html.png"));
        return defaultIcon;
    }
}

void WebView::reload()
{
    m_progress = 0;
//    QWebEngineView::reload();
    QWebEngineView::setUrl(url());
}
